import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/api/user.dart';
import 'package:flutter_enjoy_plus/utils/EvenBus.dart';
import 'package:flutter_enjoy_plus/utils/PromptAction.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key, required this.userInfo});
  final Map userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  // 是否选择了图片 -- 类似节流阀 -- 防止没有选择图片上传
  bool isSelectImage = false;
  // 是否正在上传图片 -- 节流阀 -- 防止多次点击上传
  bool isUploadingImage = false;
  // 图片名称
  String imageName = '';
  // 昵称组件控制器
  final TextEditingController _nicknameController = TextEditingController();
  // 获取头像组件
  Widget getAvatar() {
    if (widget.userInfo['avatar'] != null && widget.userInfo['avatar'] != '') {
      if ((widget.userInfo['avatar'] as String).startsWith('/data')) {
        // 适配鸿蒙端，因为鸿蒙端imagePacker返回的是/data开头的沙箱环境目录
        return Image.file(
          File(widget.userInfo['avatar']),
          width: 30,
          height: 30,
        );
      }
      return Image.network(
        widget.userInfo['avatar'],
        width: 30,
        height: 30,
      );
    }
    return Image.asset(
      'assets/images/avatar_1.jpg',
      width: 30,
      height: 30,
    );
  }

  // 更新用户信息
  void _updateUserInfo() async {
    if (_nicknameController.text.isEmpty) {
      Promptaction.showToast('用户名不能为空');
      return;
    }
    RegExp reg = RegExp(r'^[\u4e00-\u9fa5a-zA-Z0-9_]{2,18}$');
    if (!reg.hasMatch(_nicknameController.text)) {
      Promptaction.showError('用户名格式不正确');
    }
    //  上传图片
    if (!isUploadingImage) {
      if (isSelectImage) {
        // 开始上传图片
        // 生成formdata对象
        FormData fd = FormData.fromMap({
          "file": MultipartFile.fromBytes(
            await XFile(widget.userInfo['avatar']).readAsBytes(),
            filename: imageName,
            contentType: DioMediaType("image", "png"),
          ),
          "type": "image"
        });
        final res = await uploadFileAPI(fd);
        setState(() {
          widget.userInfo['avatar'] = res['url'];
        });
      }
    } else {
      Promptaction.showToast('图片正在上传中，请勿重复点击');
    }

    // 保存昵称
    await updateUserInfoAPI({
      'nickName': _nicknameController.text,
      "avatar": widget.userInfo["avatar"],
    });
    // 是否选择图片 -> false
    isSelectImage = false;
    // 上传状态 -> false
    isUploadingImage = false;
    Promptaction.showToast('保存成功');
    eventBus.fire(LoginEvent());
  }

  // 选择图片
  void _selectImage() async {
    // 创建实例
    ImagePicker picker = ImagePicker();
    XFile? image = await picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      isSelectImage = true;
      // image.path bolo 本地的临时路径，可用于查看图片
      imageName = image.name;
      Promptaction.showToast('图片选择成功');
      setState(() {
        widget.userInfo['avatar'] = image.path;
      });
      // 关闭弹窗
      if (mounted) {
        Navigator.pop(context);
      }
    }
  }

  // 显示选择头像弹层
  void _showAvatarDialog() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
            width: double.infinity,
            height: 180,
            child: Column(
              children: [
                Container(
                  alignment: Alignment.center,
                  height: 60,
                  decoration: const BoxDecoration(
                      border: Border(
                          bottom: BorderSide(width: 0.5, color: Colors.grey))),
                  child: const Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.camera_alt),
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        "拍照",
                        style: TextStyle(fontSize: 20),
                      )
                    ],
                  ),
                ),
                Container(
                    alignment: Alignment.center,
                    height: 60,
                    decoration: const BoxDecoration(
                        border: Border(
                            bottom:
                                BorderSide(width: 0.5, color: Colors.grey))),
                    child: GestureDetector(
                      // 不设置和默认的点击行为为透明，即只有点击了有内容的子元素才能触发，需要设置为不透明的状态
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        _selectImage();
                      },
                      child: const Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.photo_album),
                          SizedBox(
                            width: 10,
                          ),
                          Text(
                            "相册",
                            style: TextStyle(fontSize: 20),
                          )
                        ],
                      ),
                    )),
                Container(
                  alignment: Alignment.center,
                  height: 60,
                  child: GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.cancel_outlined),
                        SizedBox(
                          width: 10,
                        ),
                        Text(
                          "取消",
                          style: TextStyle(fontSize: 20),
                        )
                      ],
                    ),
                  ),
                )
              ],
            ),
          );
        });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (widget.userInfo['nickName'] != null &&
        widget.userInfo['nickName'] != '') {
      setState(() {
        _nicknameController.text = widget.userInfo['nickName'];
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text(
                  '头像',
                  style: TextStyle(fontSize: 16),
                ),
                const Spacer(),
                GestureDetector(
                  onTap: () {
                    _showAvatarDialog();
                  },
                  child: Row(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: getAvatar(),
                      ),
                      const Icon(Icons.arrow_forward_ios, size: 12)
                    ],
                  ),
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: _nicknameController,
                  decoration: const InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          ),
          const SizedBox(
            height: 20,
          ),
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    // 更新用户信息
                    _updateUserInfo();
                  },
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                    ),
                  ),
                ),
              )
            ],
          )
        ],
      ),
    );
  }
}
